import java.util.concurrent.locks.StampedLock;

public class Stamped {

    public static void main(String[] args) {
        System.out.println("stampedLock.");

    }
}



class Point {
    private final StampedLock stampedLock = new StampedLock();
    private double x ;
    private double y ;

    
    
    
    public void move(double deltaX, double deltaY){
        long stamp = stampedLock.writeLock();
        try {
            x += deltaX;
            y += deltaY;
        } catch (Exception e) {
            //TODO: handle exception
        }finally{
            stampedLock.unlockWrite(stamp);
        }
    }


    public double distanceFromOrigin(){
        long stamp = stampedLock.tryOptimisticRead(); // get 乐观锁(乐观锁其实不上锁，只检查版本号) , 返回版本号

        // 注意下面两行代码不是原子操作
        double currentX = x;
        double currentY = y;

        if(!stampedLock.validate(stamp)){   // 检查乐观读锁后是否有其他写锁发生 , 版本号不变，验证成功

            stamp = stampedLock.readLock(); // 获取一个悲观读锁
            try {
                currentX = x;
                currentY = y;
            } catch (Exception e) {
                //TODO: handle exception
            }finally{
                stampedLock.unlockRead(stamp); // 释放悲观读锁
            }
        }

        return Math.sqrt(currentX * currentX + currentY * currentY);
    }



}

